import http from "http"
import url from "url"
import path from "path"
import fs from "fs"
import qs from "querystring"
let obj = {
    css: "text:css;charset=utf-8",
    txt: "text:txt;charset=utf-8",
    js: "text:js;charset=utf-8",
    html: "text:html;charset=utf-8",


}
const server = http.createServer((req, res) => {

    let ourl = url.parse(req.url)//请求地址栏信息对象

    let {
        pathname,
        query
    } = ourl
    let urls = path.join(__dirname, pathname)
    let {
        user,
        pass
    } = qs.parse(query)
    // console.log(url.parse(req.url));
    // met(req,res)
    console.log(user, pass);
    // console.log(pathname);
    // console.log(req.method);
    let last = urls.slice(urls.lastIndexOf(".") + 1)
    if (fs.existsSync(urls)) {
        if (fs.statSync(urls).isFile()) {
            let str = fs.readFileSync(urls)
            if (obj[last]){
                res.writeHead(200, "ok", {
                    "content-type": obj[last]
                })
                res.write(str)
                res.end()
                return;
            }
        }
    }
    //登录接口

    if (pathname === "/login" && req.method === "GET") {
        console.log('访问成共');
        //解构请求栏
        // let {
        //     user,
        //     pass
        // } = qs.parse(query)
        //获取数据文件夹
        let jsonStr = readFlie(path.join(__dirname, "/public/json.json"))
        console.log(jsonStr);
        //将json 格式的数据成 obj
        let arr = JSON.parse(jsonStr)
        //根据数据判断 用户名和密码是否正确
        if (arr.find(item => item["user"] === user)) {
            if (arr.find(item => item["pass"] === pass)) {
                // resret({ num: 200, ok:"ok", pin:"text/plain;charset=utf-8", text:"登录成功",res,})
                resret({
                    res,
                    text: "登录成功"
                })
            } else {
                resret({
                    res,
                    text: "密码错误"
                })
            }
        } else {
            resret({
                res,
                text: "账号不存在"
            })
        }

        return;
    }
    //注册接口
    if (pathname === "/registry" && req.method === "POST") {
        console.log("注册接口进入");
        console.log(req.method);
        //创建 buffer 池
        let buf = Buffer.alloc(0);
        req.on("data", chunk => { //获取每次接收到的 buffer数据
            buf = Buffer.concat([buf, chunk])
        })
        req.on("end", () => {
            let {
                user,
                pass
            } = qs.parse(buf.toString()) //解构通过buffer池接收到的数据
            let jsonStr = readFlie(path.join(__dirname, "/public/json.json"))
            let arr = JSON.parse(jsonStr)
            if (arr.find(item => item["user"] === user)) {
                resret({
                    res,
                    text: "用户名已存在"
                })
            } else {
                arr.push({
                    "user": user,
                    "pass": pass
                })
                writeFlie(path.join(__dirname, "/public/json.json"), JSON.stringify(arr))
                resret({
                    res,
                    text: "注册成功"
                })

            }
        })

    }
    // res.end("404")
})

server.listen(5000, () => {})
//文件读取
function readFlie(src, utf) {
    utf = utf ? utf : "utf-8"
    if (fs.existsSync(src)) {
        if (fs.statSync(src).isFile()) {
            console.log("读取文件完毕！！！");
            return fs.readFileSync(src, utf)
        }
    }
}
//接口封装
function met(req, res) {
    //判断请求方式
    switch (req.method) {
        case "GET": //GET请求
            //获取请求信息  
            let ourl = url.parse(req.url)

            let {
                pathname,
                query
            } = ourl
            let urls = path.join(__dirname, pathname)
            let {
                user,
                pass
            } = qs.parse(query)
            /*
          Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '/favicon.ico',
  path: '/favicon.ico',
  href: '/favicon.ico'
}*/
            ;
            break
        case "POST": //POST请求
            //获取请求信息
            ;
            break

    }
    //获取请求信息
    //解构请求信息
    //获取数据库相对应的数据信息
    //信息比对
    //比对成功执行响应操作（增删改查）
}
//文件写入
function writeFlie(src, text, utf) {
    utf = utf ? utf : "utf-8"
    text = text ? text : ""
    fs.writeFileSync(src, text, utf)
    console.log("写入文件完毕！！！");
}
//返回数据
function resret(obj) {
    obj.num = obj.num ? obj.num : 200
    obj.ok = obj.ok ? obj.ok : "ok"
    obj.pin = obj.pin ? obj.pin : "text/plain;charset=utf-8"
    obj.res.writeHead(obj.num, obj.ok, {
        "content-type": obj.pin
    })
    obj.res.end(obj.text)
}